package org.example.business;// -*- coding: utf-8 -*-

// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.

// Licensed under the Amazon Software License (the "License"). You may not use this file except in
// compliance with the License. A copy of the License is located at

//    http://aws.amazon.com/asl/

// or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific
// language governing permissions and limitations under the License.

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.oauth2.model.AccessTokenModel;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;
import com.amazonaws.services.lambda.runtime.Context;
import lombok.extern.slf4j.Slf4j;
import org.example.utils.HttpTool;
import org.example.utils.MapUrlParamsTool;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.UUID;

@Component
@Slf4j
public class AlexaHandler {

    public void handler(InputStream inputStream, OutputStream outputStream, Context context) {
        String request;
        try {
            request = getRequest(inputStream);
            System.out.println("Request:");
            System.out.println(request);

            JSONObject jsonRequest = JSONObject.parseObject(request);
            JSONObject directive = jsonRequest.getJSONObject("directive");
            JSONObject header = directive.getJSONObject("header");

            AlexaResponse ar;

            String namespace = header.containsKey("namespace") ? header.getString("namespace") :  "INVALID";
            String correlationToken = header.containsKey("correlationToken") ? header.getString("correlationToken") :  "INVALID";

            JSONObject jsonObject = new JSONObject();
            String str = "";
            String uuid = UUID.randomUUID().toString();

            switch(namespace) {

                case "Alexa.Authorization":
                    System.out.println("Found Alexa.Authorization Namespace");
                    JSONObject payload = directive.getJSONObject("payload");
                    String token1 = payload.getJSONObject("grantee").getString("token");
                    String refreshToken = SaManager.getSaTokenDao().get(token1);
                    AccessTokenModel accessTokenModel = SaOAuth2Util.refreshAccessToken(refreshToken);
                    ar = new AlexaResponse("Alexa.Authorization","AcceptGrant", "INVALID", "INVALID", correlationToken);



//                    str = "{\"event\":{\"header\":{\"namespace\":\"Alexa.Authorization\"," +
//                            "\"name\":\"AuthorizationGrantResponse\"," +
//                            "\"messageId\":\"" + uuid + "\",\"payloadVersion\":\"3\"}," +
//                            "\"payload\":{\"code\":\"SUCCESS\",\"accessToken\":\"" + accessTokenModel.accessToken + "\",\"refreshToken\":\"" + accessTokenModel.refreshToken + "\",\"tokenType\":\"Bearer\",\"expiresIn\":" + accessTokenModel.getExpiresIn() + "}}}";

                    str = "{\"event\":{\"header\":{\"namespace\":\"Alexa.Authorization\",\"name\":\"AcceptGrant.Response\",\"messageId\":\"" + uuid + "\",\"payloadVersion\":\"3\"},\"payload\":{}}}";

                    jsonObject = JSONObject.parseObject(str);
                    break;

                case "Alexa.Discovery":
                    System.out.println("Found Alexa.Discovery Namespace");
                    ar = new AlexaResponse("Alexa.Discovery", "Discover.Response");
                    String capabilityAlexa = ar.CreatePayloadEndpointCapability("AlexaInterface", "Alexa.CameraStreamController", "3", null);
                    String capabilityAlexaPowerController = ar.CreatePayloadEndpointCapability("AlexaInterface", "Alexa.CameraStreamController", "3", "{\"supported\": [ { \"name\": \"powerState\" } ] }");
                    String capabilities = "[" + capabilityAlexa + ", " + capabilityAlexaPowerController + "]";
                    ar.AddPayloadEndpoint("Sample Switch", "sample-switch-01", capabilities);

                    str = "{\"event\":{\"header\":{\"namespace\":\"Alexa.Discovery\",\"name\":\"Discover.Response\",\"payloadVersion\":\"3\",\"messageId\":\" " + uuid + " \"}," +
                            "\"payload\":{\"endpoints\":[" +
//                            "{\"endpointId\":\"camera-RTC-001\",\"manufacturerName\":\"YourCompany\",\"description\":\"Front Door RTC Camera\",\"friendlyName\":\"My front door RTC camera doorbell\",\"displayCategories\":[\"CAMERA\"],\"cookie\":{},\"capabilities\":[{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.RTCSessionController\",\"version\":\"3\",\"configuration\":{\"isFullDuplexAudioSupported\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.EndpointHealth\",\"version\":\"3.1\",\"properties\":{\"supported\":[{\"name\":\"connectivity\"}],\"proactivelyReported\":true,\"retrievable\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa\",\"version\":\"3\"}]}" +
//                            "," +
//                            "{\"endpointId\":\"camera-001\",\"manufacturerName\":\"YourCompany\",\"description\":\"Camera by YourCompany\",\"friendlyName\":\"Front door camera\",\"displayCategories\":[\"CAMERA\"],\"cookie\":{},\"capabilities\":[{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.CameraStreamController\",\"version\":\"3\",\"properties\":{\"supported\":[{\"name\":\"cameraStream\"}],\"proactivelyReported\":false,\"retrievable\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.EndpointHealth\",\"version\":\"3.1\",\"properties\":{\"retrievable\":true,\"supported\":[{\"name\":\"connectivity\"}],\"proactivelyReported\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa\",\"version\":\"3\"}]}" +
//                            "{\"endpointId\":\"camera-001\",\"manufacturerName\":\"YourCompany\",\"description\":\"Camera by YourCompany\",\"friendlyName\":\"Front door camera\",\"displayCategories\":[\"CAMERA\"],\"cookie\":{},\"capabilities\":[{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.CameraStreamController\",\"version\":\"3\",\"properties\":{\"supported\":[{\"name\":\"cameraStream\"}],\"proactivelyReported\":false,\"retrievable\":true}}]}" +
//                            "{\"endpointId\":\"camera-001\",\"manufacturerName\":\"YourCompany\",\"friendlyName\":\"Front Door Camera\",\"description\":\"Camera by YourCompany\",\"displayCategories\":[\"CAMERA\"],\"capabilities\":[{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.CameraStreamController\",\"version\":\"3\",\"cameraStreamConfigurations\":[{\"protocols\":[\"RTSP\"],\"resolutions\":[{\"width\":960,\"height\":600}],\"authorizationTypes\":[\"BASIC\"],\"videoCodecs\":[\"H264\"],\"audioCodecs\":[\"AAC\"]}]}]}" +
                           // RTCSessionController


                            "{\"endpointId\":\"QS4202400000141\",\"manufacturerName\":\"qamsong\",\"description\":\"test\",\"friendlyName\":\"one camera\",\"displayCategories\":[\"CAMERA\"],\"capabilities\":[{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.DoorbellEventSource\",\"version\":\"3\",\"proactivelyReported\":true},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.RTCSessionController\",\"version\":\"3\",\"configuration\":{\"isFullDuplexAudioSupported\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.MediaMetadata\",\"version\":\"3\",\"proactivelyReported\":true},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.EndpointHealth\",\"version\":\"3\",\"properties\":{\"supported\":[{\"name\":\"connectivity\"}],\"proactivelyReported\":true,\"retrievable\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa\",\"version\":\"3\"}]}" +
                            ",{\"endpointId\":\"QS3202400000195\",\"manufacturerName\":\"qamsong\",\"description\":\"test\",\"friendlyName\":\"two camera\",\"displayCategories\":[\"CAMERA\"],\"capabilities\":[{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.DoorbellEventSource\",\"version\":\"3\",\"proactivelyReported\":true},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.RTCSessionController\",\"version\":\"3\",\"configuration\":{\"isFullDuplexAudioSupported\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.MediaMetadata\",\"version\":\"3\",\"proactivelyReported\":true},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.EndpointHealth\",\"version\":\"3\",\"properties\":{\"supported\":[{\"name\":\"connectivity\"}],\"proactivelyReported\":true,\"retrievable\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa\",\"version\":\"3\"}]}" +

                            // CameraStreamController
//                            ",{\"displayCategories\":[\"CAMERA\"],\"capabilities\":[{\"cameraStreamConfigurations\":[{\"audioCodecs\":[\"acc\"],\"authorizationTypes\":[\"BASIC\"],\"videoCodecs\":[\"h264\"],\"resolutions\":[{\"width\":960,\"height\":600}],\"protocols\":[\"RTSP\"]}],\"type\":\"AlexaInterface\",\"interface\":\"Alexa.CameraStreamController\",\"version\":\"3\"},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.MediaMetadata\",\"version\":\"3\",\"proactivelyReported\":true},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.EndpointHealth\",\"version\":\"3\",\"properties\":{\"retrievable\":true,\"supported\":[{\"name\":\"connectivity\"}],\"proactivelyReported\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa\",\"version\":\"3\"}],\"cookie\":{},\"endpointId\":\"QS4202400000141\",\"manufacturerName\":\"qamsong\",\"description\":\"test\",\"friendlyName\":\"AI camera\"}" +
//                            ",{\"displayCategories\":[\"CAMERA\"],\"capabilities\":[{\"cameraStreamConfigurations\":[{\"audioCodecs\":[\"acc\"],\"authorizationTypes\":[\"BASIC\"],\"videoCodecs\":[\"h264\"],\"resolutions\":[{\"width\":960,\"height\":600}],\"protocols\":[\"RTSP\"]}],\"type\":\"AlexaInterface\",\"interface\":\"Alexa.CameraStreamController\",\"version\":\"3\"},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.MediaMetadata\",\"version\":\"3\",\"proactivelyReported\":true},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa.EndpointHealth\",\"version\":\"3\",\"properties\":{\"retrievable\":true,\"supported\":[{\"name\":\"connectivity\"}],\"proactivelyReported\":true}},{\"type\":\"AlexaInterface\",\"interface\":\"Alexa\",\"version\":\"3\"}],\"cookie\":{},\"endpointId\":\"QS3202400000195\",\"manufacturerName\":\"qamsong\",\"description\":\"test\",\"friendlyName\":\"AI camera 195\"}" +

                            "]}}}";
                    jsonObject = JSONObject.parseObject(str);

                    break;

                case "Alexa.PowerController":
                    System.out.println("Found Alexa.PowerController Namespace");
                    String endpointId = directive.getJSONObject("endpoint").containsKey("endpointId") ? directive.getJSONObject("endpoint").getString("endpointId") : "INVALID";
                    String token = directive.getJSONObject("endpoint").getJSONObject("scope").containsKey("token") ? directive.getJSONObject("endpoint").getJSONObject("scope").getString("token") : "INVALID";
                    String powerStateValue = directive.getJSONObject("header").containsKey("name") ? directive.getJSONObject("header").getString("name") : "TurnOn";
                    String value = powerStateValue.equals("TurnOn") ? "ON" : "OFF";

                    // Set the value in the DynamodDB table SampleSmartHome
                    if(sendDeviceState(endpointId, "powerState", value)) {
                        ar = new AlexaResponse("Alexa", "Response", endpointId, token, correlationToken);
                        ar.AddContextProperty("Alexa.PowerController", "powerState", value, 200);
                    }
                    else {
                        ar = new AlexaResponse("Alexa", "ErrorResponse");
                    }

                    break;

                case "Alexa.CameraStreamController":
                    System.out.println("Found Alexa.CameraStreamController Namespace");
                    JSONObject endpoint1 = directive.getJSONObject("endpoint");
                    String token3 = endpoint1.getJSONObject("scope").getString("token");
                    String endpointId3 = endpoint1.getString("endpointId");
//                    str = "{\"event\":{\"header\":{\"namespace\":\"Alexa.CameraStreamController\",\"name\":\"Response\",\"payloadVersion\":\"3\",\"messageId\":\"" + uuid + "\",\"correlationToken\":\"" + correlationToken + "\"}," +
//                            "\"endpoint\":{\"endpointId\":\"QS4202400000141\", \"scope\": {\"type\": \"BearerToken\",\"token\": \"" + token3 + "\"}},\"payload\":{\"cameraStreams\":[{\"uri\":\"rtsp://ap1-video-mediaserver2.botslab.com:443/QS4202400000141_f431bda34fb3c38b_0\",\"expirationTime\":\"2024-07-10T14:30:05Z\",\"protocol\":\"RTSP\",\"resolution\":{\"width\":960,\"height\":600},\"authorizationType\":\"BASIC\",\"videoCodec\":\"H264\",\"audioCodec\":\"AAC\"}]}}}";

                    // 360
                    int idleTimeoutSeconds = 30;
                    String expirationTime = "2024-08-10T14:30:05Z";
                    String strCamera = vcloudStream(endpointId3, idleTimeoutSeconds, expirationTime, 0, "", "", "");
                    JSONObject jsonObjectCamera = JSON.parseObject(strCamera);
                    String url = jsonObjectCamera.getJSONObject("data").getJSONObject("stream_info").getString("stream_url");
//                    url = url.replace("rtsp", "rtsps");
                    String height = jsonObjectCamera.getJSONObject("data").getJSONObject("stream_info").getJSONObject("resolution").getString("height");
                    String width = jsonObjectCamera.getJSONObject("data").getJSONObject("stream_info").getJSONObject("resolution").getString("width");
                    String audio_codec = jsonObjectCamera.getJSONObject("data").getJSONObject("stream_info").getString("audio_codec");
                    String authorization_type = jsonObjectCamera.getJSONObject("data").getJSONObject("stream_info").getString("authorization_type");
                    String video_codec = jsonObjectCamera.getJSONObject("data").getJSONObject("stream_info").getString("video_codec");
                    str = "{\"event\":{\"header\":{\"payloadVersion\":\"3\",\"namespace\":\"Alexa.CameraStreamController\",\"name\":\"Response\",\"messageId\":\"" + uuid + "\",\"correlationToken\":\"" + correlationToken + "\"}," +
                            "\"endpoint\":{\"cookie\": {},\"endpointId\":\"" + endpointId3 + "\",\"scope\":{\"type\":\"BearerToken\",\"token\":\"" + token3 + "\"}},\"payload\":{\"imageUri\": \"\",\"cameraStreams\":[{\"protocol\":\"RTSP\",\"expirationTime\":\"" + expirationTime + "\",\"idleTimeoutSeconds\":" + idleTimeoutSeconds + ",\"authorizationType\":\"" + authorization_type + "\",\"audioCodec\":\"" + audio_codec + "\",\"uri\":\"" + url + "\",\"resolution\":{\"width\":"+ width +",\"height\":" + height + "},\"videoCodec\":\"" + video_codec + "\"}]},\"context\":{\"properties\":[{\"namespace\":\"Alexa.EndpointHealth\",\"name\":\"connectivity\",\"value\":{\"value\":\"OK\"},\"timeOfSample\":\"" + expirationTime + "\",\"uncertaintyInMilliseconds\":0}]}}}";


                    // 测试
//                    str = "{\"event\":{\"header\":{\"payloadVersion\":\"3\",\"namespace\":\"Alexa.CameraStreamController\",\"name\":\"Response\",\"messageId\":\"" + uuid + "\",\"correlationToken\":\"" + correlationToken + "\"}," +
//                            "\"endpoint\":{\"cookie\": {},\"endpointId\":\"QS4202400000141\",\"scope\":{\"type\":\"BearerToken\",\"token\":\"" + token3 + "\"}},\"payload\":{\"imageUri\": \"\",\"cameraStreams\":[{\"protocol\":\"RTSP\",\"expirationTime\":\"2024-08-10T14:30:05Z\",\"idleTimeoutSeconds\":100,\"authorizationType\":\"NONE\",\"audioCodec\":\"acc\",\"uri\":\"rtsp://116.196.73.156:443/mystream\",\"resolution\":{\"width\":512,\"height\":288},\"videoCodec\":\"h264\"}]},\"context\":{\"properties\":[{\"namespace\":\"Alexa.EndpointHealth\",\"name\":\"connectivity\",\"value\":{\"value\":\"OK\"},\"timeOfSample\":\"2024-07-06T15:18:25Z\",\"uncertaintyInMilliseconds\":0}]}}}";


                    jsonObject = JSONObject.parseObject(str);



                    break;

                case "Alexa.RTCSessionController":
                    System.out.println("Found Alexa.RTCSessionController Namespace");
                    String name = header.getString("name");

                    JSONObject endpoint = directive.getJSONObject("endpoint");
                    String token2 = endpoint.getJSONObject("scope").getString("token");

                    String ss = "";

                    switch (name) {
                        case "InitiateSessionWithOffer":
                            String s = uuid.replace("-", "");
                            JSONObject payload11 = directive.getJSONObject("payload");

                            int idleTimeoutSeconds1 = 300;
                            String expirationTime1 = "2024-08-10T14:30:05Z";
                            String sessionId1 = payload11.getString("sessionId");
                            String sdpInfo = payload11.getJSONObject("offer").getString("value");
                            String endpointId4 = endpoint.getString("endpointId");

                            String id = endpointId4.replace("_rtc", "");
                            String strRtc = vcloudStream(id, idleTimeoutSeconds1, expirationTime1, 4, "rtc", sessionId1, sdpInfo);
                            JSONObject jsonObjectRtc = JSON.parseObject(strRtc);
                            String sdp = jsonObjectRtc.getJSONObject("data").getJSONObject("stream_info").getString("sdp");

                            ss = "{\"event\":{\"header\":{\"namespace\":\"Alexa.RTCSessionController\",\"name\":\"AnswerGeneratedForSession\",\"messageId\":\"" + uuid + "\"," +
                                    "\"correlationToken\":\"" + correlationToken + "\",\"payloadVersion\":\"3\"},\"endpoint\":{\"scope\":{\"type\":\"BearerToken\"," +
                                    "\"token\":\"" + token2 + "\"},\"endpointId\":\"" + endpointId4 + "\"}," +
                                    "\"payload\":{\"answer\":{\"format\":\"SDP\",\"value\":\"" + sdp + "\"}}" +
//                                    "\"payload\":{\"sessionId\":\"" + s + "\",\"sessionTimeoutInSeconds\":30,\"protocols\":[{\"protocolName\":\"HLS\",\"requestHeaders\":{},\"uri\":\" https://content.jwplatform.com/manifests/vM7nH0Kl.m3u8\"}]}" +
                                    "}}";
                            jsonObject = JSONObject.parseObject(ss);
                            break;

                        case "SessionConnected":
                            JSONObject payload1 = directive.getJSONObject("payload");
                            String sessionId = payload1.getString("sessionId");
                            ss = "{\"event\":{\"header\":{\"namespace\":\"Alexa.RTCSessionController\",\"name\":\"SessionConnected\",\"messageId\":\"" + uuid + "\"," +
                                    "\"correlationToken\":\"" + correlationToken + "\",\"payloadVersion\":\"3\"},\"endpoint\":{\"scope\":{\"type\":\"BearerToken\"," +
                                    "\"token\":\"" + token2 + "\"},\"endpointId\":\"camera-RTC-001\"},\"payload\":{\"sessionId\":\"" + sessionId + "\"}}}";
                            jsonObject = JSONObject.parseObject(ss);
                            break;

                        case "SessionDisconnected":
                            JSONObject payload2 = directive.getJSONObject("payload");
                            String sessionId2 = payload2.getString("sessionId");
                            ss = "{\"event\":{\"header\":{\"namespace\":\"Alexa.RTCSessionController\",\"name\":\"SessionDisconnected\",\"messageId\":\"" + uuid + "\"," +
                                    "\"correlationToken\":\"" + correlationToken + "\",\"payloadVersion\":\"3\"},\"endpoint\":{\"scope\":{\"type\":\"BearerToken\"," +
                                    "\"token\":\"" + token2 + "\"},\"endpointId\":\"camera-RTC-001\"},\"payload\":{\"sessionId\":\"" + sessionId2 + "\"}}}";
                            jsonObject = JSONObject.parseObject(ss);
                            break;
                    }

                    break;

                default:
                    System.out.println("INVALID Namespace");
                    ar = new AlexaResponse();
                    break;
            }

            System.out.println("Response:");
            System.out.println(jsonObject);

            outputStream.write(jsonObject.toJSONString().getBytes(Charset.forName("UTF-8")));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    static boolean sendDeviceState(String endpoint_id, String state, String value) {

        String attributeValue = state + "Value";

        AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
        DynamoDB dynamoDB = new DynamoDB(client);

        Table table = dynamoDB.getTable("SampleSmartHome");

        UpdateItemSpec updateItemSpec =
                new UpdateItemSpec()
                        .withPrimaryKey("ItemId", endpoint_id)
                        .withUpdateExpression("set #v = :val1")
                        .withNameMap(new NameMap().with("#v", attributeValue))
                        .withValueMap(new ValueMap().withString(":val1", value))
                        .withReturnValues(ReturnValue.ALL_NEW);

        UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
//        System.out.println(outcome.getItem().toJSONPretty());

        return true;
    }

    static String getRequest(InputStream is) {
        Scanner s = new Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

    private static String vcloudStream(String deviceName, int idleTimeoutSeconds, String expirationTime, int protocol, String sdp_type, String session_id, String sdp_info) {

        String pid = "4202400000014";
        String appKey = "29nool83ovz9";
        String appSecret = "ead22862dcd1ab54bb750a0148e64c85";
        String productKey = "d52e9b9d8c8e";

//        String url = "https://app.home.360.cn/v1/iot/device/vcloud_stream?" + getCommonParams(appKey, appSecret);
        String url = "https://ap1-sapp-api.botslab.com/v1/iot/device/vcloud_stream?" + getCommonParams(appKey, appSecret);
        /*设置请求头*/
        Map<String, String> headerParams = getAuthHeader(pid);
        /*设置body体*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("product_key", productKey);
        jsonObject.put("device_name", deviceName);
        jsonObject.put("idle_timeout_seconds", idleTimeoutSeconds);
        jsonObject.put("expiration_time", expirationTime);
        jsonObject.put("company", 0);
        jsonObject.put("protocol", protocol);
        jsonObject.put("bitrate_type", 2);
        jsonObject.put("channel", 1);
        if (!sdp_type.equals("")) {
            jsonObject.put("sdp_type", sdp_type);
        }
        if (!session_id.equals("")) {
            jsonObject.put("session_id", session_id);
        }
        if (!sdp_info.equals("")) {
            jsonObject.put("sdp_info", sdp_info);
        }
        String bodyParams = MapUrlParamsTool.getUrlParamsByMap(jsonObject);
        System.out.println("url: " + url);
        String str = HttpTool.post(url, headerParams, bodyParams);
        System.out.println("响应体：" + str);
        return str;
    }

    /**
     * 获取公共参数
     *
     * @param appKey    云云对接 ak
     * @param appSecret 云云对接 as
     * @return 公共参数
     */
    public static String getCommonParams(String appKey, String appSecret) {
        String m2 = RandomUtil.randomNumbers(32);
        String signTs = String.valueOf(System.currentTimeMillis() / 1000);
        String signNo = RandomUtil.randomNumbers(20);
        String sign = SecureUtil.md5(appKey + m2 + signTs + signNo + appSecret);

        Map<String, Object> commonParamsMap = new HashMap<>();
        commonParamsMap.put("appkey", appKey);
        commonParamsMap.put("sign_ts", signTs);
        commonParamsMap.put("sign_no", signNo);
        commonParamsMap.put("m2", m2);
        commonParamsMap.put("sign", sign);
        /*用户绑定设备*/
        return MapUrlParamsTool.getUrlParamsByMap(commonParamsMap);
    }

    public static Map<String, String> getAuthHeader(String pid) {
        Map<String, String> headerParams = new HashMap<>();
        headerParams.put("Authorization", "qid " + pid);
        System.out.println("请求头: " + headerParams);
        return headerParams;
    }
}
